import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import type { DatePickerProps } from 'antd';
import { DatePicker } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { useModel } from 'umi';
import './_style.less';

const { RangePicker } = DatePicker;

const dateFormat = 'YYYY';

interface YearRangeProps {
  startDate: string; //2022
  endDate: string; //2024
  disabled?: boolean;
  onChangeCallBack?: any;
}

export interface FowardRefYearRange {
  getYearDateValue: () => {
    startYear: string;
    endYear: string;
    dates: string[];
  };
}

function devalueDate(startDateStr: string, endDateStr: string): any {
  if (!startDateStr || !endDateStr) {
    return null;
  }
  const date = [
    dayjs(startDateStr.toString(), dateFormat),
    dayjs(endDateStr.toString(), dateFormat),
  ];
  return date;
}

const YearRange = forwardRef(
  (props: YearRangeProps, ref: React.ForwardedRef<FowardRefYearRange>) => {
    const { startDate, endDate, disabled = false, onChangeCallBack = () => {} } = props;
    const ztModel = useModel('ztModel');

    const { ztDates } = ztModel;
    // 记录上一次,传递进来的props
    const lastDateRef = useRef<YearRangeProps>({
      startDate: '',
      endDate: '',
    });

    // 初始化props
    const [rangeValue, setRangeValue] = useState<any>(['', '']);

    const rangePickerRef = useRef<any>();

    // 对比props, props如果有变化则以props为准;
    useEffect(() => {
      const { startDate: lastStartDate, endDate: lastEndDate } = lastDateRef.current;
      if (startDate !== lastStartDate || endDate !== lastEndDate) {
        setRangeValue(devalueDate(startDate, endDate));
      }
      lastDateRef.current = {
        startDate,
        endDate,
      };
    }, [startDate, endDate]);

    useImperativeHandle(
      ref,
      () => {
        return {
          getYearDateValue: () => {
            const startYear = rangeValue[0] ? rangeValue[0].year() : '';
            const endYear = rangeValue[1] ? rangeValue[1].year() : '';
            const dates = [];
            for (let i = startYear; i <= endYear; i++) {
              dates.push(i);
            }
            return {
              startYear,
              endYear,
              dates,
            };
          },
        };
      },
      [rangeValue],
    );

    /**
     * 日期范围change
     * @param value
     * @param dateString
     */
    const onChange = (
      value: DatePickerProps['value'] | RangePickerProps['value'],
      dateString: [string, string] | string,
    ) => {
      console.log('Formatted Selected Time: ', dateString);
      setRangeValue(value);
    };
    const disabledDate = (current: any) => {
      if (ztDates && ztDates.length) {
        const startYear = ztDates[0] || '';
        const endYear = ztDates[ztDates.length - 1] || '';
        return !(current.year() >= startYear && current.year() <= endYear);
      }
      return false;
    };
    return (
      <>
        <RangePicker
          className="custom-rangepicker"
          allowClear={false}
          picker="year"
          ref={rangePickerRef}
          value={rangeValue}
          onChange={onChange}
          disabled={disabled}
          disabledDate={disabledDate}
          onOpenChange={onChangeCallBack.bind(this, rangeValue)}
          popupClassName={'custom-rangepicker'}
        />
      </>
    );
  },
);

export default YearRange;
